﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using University.Workshop.DataAccess;
using University.Workshop.Model;
using System.Globalization;
using System.IO;
using System.Web.Security;
using System.Collections.ObjectModel;
using University.Workshop.Business;
using System.Net.Mail;

namespace University.Workshop.WebApp
{
    public partial class ModifyProduct : System.Web.UI.Page
    {
       

        protected void Grid_PageIndexChanged(object source, DataGridPageChangedEventArgs e)
        {
            ProductGrid.CurrentPageIndex = e.NewPageIndex;
            BindData();
        }

        protected void Grid_EditCommand(object source, DataGridCommandEventArgs e)
        {
            try
            {
                long productId = Int64.Parse(ProductGrid.Items[e.Item.ItemIndex].Cells[0].Text);
                Product prod = ProductDataAccess.GetProductById(productId);

                prodToChange.Text = prod.ProductId.ToString();
                ProductGrid.SelectedIndex = e.Item.ItemIndex;
                LoadInformation(prod);
                BindData();
            }
            catch (Exception ex)
            {
                errorMsg.Visible = true;
                errorMsg.Text = ex.Message;
            }
        }

        public void LoadInformation(Product prod)
        {
            


            productInformation.Visible = true;
            xName.Text = prod.Name;
            xQuantity.Text = prod.Quantity.ToString(CultureInfo.InvariantCulture);
            description.Text = prod.Description;
            category.SelectedIndex = category.Items.IndexOf(new ListItem { Value = prod.Category, Text = prod.Category });
            if (prod.Currency == "Bolivianos")
                rBolivianos.Checked = true;
            else
                rDollars.Checked = true;
            xPrice.Text = prod.Price.ToString();
            if (Directory.Exists(Server.MapPath("~/Thumbnails/") + prod.ProductId + "/"))
            {
                DirectoryInfo dir = new DirectoryInfo(Server.MapPath("~/Thumbnails/") + prod.ProductId + "/");
                FileInfo[] currentImages = dir.GetFiles();
                string thumbUrl = "~/Thumbnails/" + prod.ProductId + "/";
                foreach (FileInfo fi in currentImages)
                {
                    if (String.IsNullOrEmpty(image1.ImageUrl))
                    {
                        image1.ImageUrl = thumbUrl + fi.Name;
                        rmImg1.Visible = true;
                        img1.Visible = false;
                    }
                    else if (String.IsNullOrEmpty(image2.ImageUrl))
                    {
                        image2.ImageUrl = thumbUrl + fi.Name;
                        rmImg2.Visible = true;
                        img2.Visible = false;
                    }
                    else if (String.IsNullOrEmpty(image3.ImageUrl))
                    {
                        image3.ImageUrl = thumbUrl + fi.Name;
                        rmImg3.Visible = true;
                        img3.Visible = false;
                    }
                    else if (String.IsNullOrEmpty(image4.ImageUrl))
                    {
                        image4.ImageUrl = thumbUrl + fi.Name;
                        rmImg4.Visible = true;
                        img4.Visible = false;
                    }
                    else if (String.IsNullOrEmpty(image5.ImageUrl))
                    {
                        image5.ImageUrl = thumbUrl + fi.Name;
                        rmImg5.Visible = true;
                        img5.Visible = false;
                    }
                }
            }
            quantityLabel.Text = prod.Quantity.ToString();

        }

        public void BindData()
        {
            ProductGrid.DataSource = ProductDataAccess.GetProductsBySeller(UserDataAccess.GetUserByEmail(User.Identity.Name).Id);
            ProductGrid.DataBind();
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!User.Identity.IsAuthenticated)
                FormsAuthentication.RedirectToLoginPage();
            else
            {
                errorMsg.Visible = false;
                try
                {
                    if (!Page.IsPostBack)
                    {
                        BindData();
                        productInformation.Visible = false;
                    }
                }
                catch (Exception ex)
                {
                    errorMsg.Text = ex.Message;
                    errorMsg.Visible = true;
                }
            }
        }

        private void DeleteImages(long productId)
        {
            string thumbDir = Server.MapPath("~/Thumbnails/") + productId + "/";
            Collection<string> imagesToDelete = new Collection<string>();
            if (!rmImg1.Visible)
            {
                string name = Path.GetFileName(image1.ImageUrl);
                FileInfo image = new FileInfo(thumbDir + name);
                if (image.Exists)
                {
                    imagesToDelete.Add(name);
                }
            }
            if (!rmImg2.Visible)
            {
                string name = Path.GetFileName(image2.ImageUrl);
                FileInfo image = new FileInfo(thumbDir + name);
                if (image.Exists)
                {
                    imagesToDelete.Add(name);
                }
            }
            if (!rmImg3.Visible)
            {
                string name = Path.GetFileName(image3.ImageUrl);
                FileInfo image = new FileInfo(thumbDir + name);
                if (image.Exists)
                {
                    imagesToDelete.Add(name);
                }
            }
            if (!rmImg4.Visible)
            {
                string name = Path.GetFileName(image4.ImageUrl);
                FileInfo image = new FileInfo(thumbDir + name);
                if (image.Exists)
                {
                    imagesToDelete.Add(name);
                }
            }
            if (!rmImg5.Visible)
            {
                string name = Path.GetFileName(image5.ImageUrl);
                FileInfo image = new FileInfo(thumbDir + name);
                if (image.Exists)
                {
                    imagesToDelete.Add(name);
                }
            }
            ImageUploadHandler.DeleteImages(imagesToDelete, Server, productId);
        }

        protected void submit_Click(object sender, EventArgs e)
        {
            try
            {
                long productId = Int64.Parse(ProductGrid.Items[ProductGrid.SelectedIndex].Cells[0].Text);
                string currency;
                if (rBolivianos.Checked)
                    currency = "Bolivianos";
                else
                    currency = "Dollars";
                Collection<HttpPostedFile> images = new Collection<HttpPostedFile>();
                HttpFileCollection uploadFilCol = Request.Files;
                for (int i = 0; i < uploadFilCol.Count; i++)
                {
                    HttpPostedFile file = uploadFilCol[i];
                    images.Add(file);
                }
                images = ProductRegistrationManager.GetUploadedFiles(images);
                bool unremovedImages = (rmImg1.Visible || rmImg2.Visible || rmImg3.Visible || rmImg4.Visible || rmImg5.Visible);
                bool hasImages = (images.Count != 0 || unremovedImages);
                Product p = ProductRegistrationManager.ModifyProduct(xName.Text, xPrice.Text, description.Text, category.SelectedValue, hasImages, currency, productId, "OnSale",xQuantity.Text);
                ImageUploadHandler.UploadImages(images, Server, productId);
                DeleteImages(p.ProductId);
                //sendMail(); error from me [sara] check!!
                Response.Redirect("ProductModificationSuccess.aspx");
            }
            catch (Exception ex)
            {
                errorMsg.Text = ex.Message;
                errorMsg.Visible = true;
            }
        }

        protected void cancel_Click(object sender, EventArgs e)
        {
            
        }

        protected void rmImg1_Click(object sender, EventArgs e)
        {
            img1.Visible = true;
            image1.Visible = false;
            rmImg1.Visible = false;
        }

        protected void rmImg2_Click(object sender, EventArgs e)
        {
            img2.Visible = true;
            image2.Visible = false;
            rmImg2.Visible = false;
        }

        protected void rmImg3_Click(object sender, EventArgs e)
        {
            img3.Visible = true;
            image3.Visible = false;
            rmImg3.Visible = false;
        }

        protected void rmImg4_Click(object sender, EventArgs e)
        {
            img4.Visible = true;
            image4.Visible = false;
            rmImg4.Visible = false;
        }

        protected void rmImg5_Click(object sender, EventArgs e)
        {
            img5.Visible = true;
            image5.Visible = false;
            rmImg5.Visible = false;
        }

        public  void sendMail()
        {
            if (Convert.ToInt64(quantityLabel.Text) == 0)
            {
                if (Convert.ToInt64(xQuantity.Text) > 0)
                {
                    GridView1.DataSource = UserWishListDataAccess.GetProductBYProductId(Convert.ToInt64(prodToChange.Text));
                    GridView1.DataBind();
                    UserWishListDataAccess.UpdateProductStatusAvailable(Convert.ToInt64(prodToChange.Text)); //change status to available in wishList
                    GridView2.DataSource = UserWishListDataAccess.UserEmail(Convert.ToInt64(prodToChange.Text));//bidn datagrid2 with the email to whom we must sent notifications
                    GridView2.DataBind();
                    foreach (GridViewRow row in GridView2.Rows)
                    {
                        MailHelper.SendMailMessage("user.loquesea@gmail.com", row.Cells[0].Text, "LQS Product's News", "Some of your WishList Products ARE AVAILABLE! Check Now!!! http://localhost:5107/Default.aspx");

                    }

                }
            }
            //MailHelper.SendMailMessage("user.loquesea@gmail.com", user.ContactInformation.Email, "LQS Product's News", "Some of your WishList Products ARE AVAILABLE! Check Now!!! http://localhost:5107/Default.aspx");
            /*User user = UserDataAccess.GetUserByEmail(User.Identity.Name);
            sendMail(user);*/
        }


    }
}